# -*- coding: utf-8 -*-
'''
@author: Hugo
@file: 生成验证码.py
@time: 2021/9/5 10:12
'''
import random
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO

def get_img():
    width, height, font_size, font_num = 300, 100, 48, 5
    bg_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0,
    255)) # 背景颜色
    image = Image.new(mode='RGB', size=(width, height), color=bg_color) # 画布
    draw = ImageDraw.Draw(image, mode='RGB')     # 绘图类
    font = ImageFont.truetype("C:\Windows\Fonts\Arial.ttf", font_size)  # 字体
    verify = str()
    for i in range(font_num):
       x = random.randint(i * (width / font_num), (i + 1) * (width / font_num) -
    font_size)
       y = random.randint(0, height - font_size)
       char = random.choice([chr(alpha) for alpha in range(65, 91)] + [str(num) for
    num in range(10)]) # 随机参数拼接给verify
       verify += char
       color = (random.randint(0, 255), random.randint(0, 255), random.randint(0,
    255))
       draw.text((x, y), char, fill=color, font=font)
    b_io = BytesIO()
    image.save(b_io,format = 'PNG')
    im_by = b_io.getvalue()  # 图片字节码
    return verify,im_by
get_img()



